package com.jarvis.du.baselibrary;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;

/**
 * Author: dyj
 * Date: 2018/11/26 16:38
 * E-mail: duyangjun1991@163.com
 */

public class FileUtils {

    /**
     * 创建目录
     * @param dirPath
     * @return
     */
    public static boolean createDir(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists() || !file.isDirectory()) {
            return file.mkdirs();
        }
        return true;
    }
    /**
     * 创建文件
     *
     * @param path
     *            文件路径
     * @param filename
     *            文件名
     * @return
     */
    public static boolean createFile(String path, String filename) {
        if(!createDir(path)) {
            return false;
        }
        String filePath = path + File.separator + filename;
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            try {
                // 创建新文件
                return file.createNewFile();
            } catch (Exception e) {
                if (BuildConfig.DEBUG) {
                    Log.e("TAG", e.getMessage(), e);
                }

            }
        }
        return true;
    }

    /**
     * 获取系统文件路径<br>
     * 当SD卡存在或者SD卡不可被移除时，获取SD卡路径；否则获取内存路径
     * @param context 上下文
     * @return 缓存路径
     */
    @SuppressLint("NewApi")
    public static String getDiskFilePath(Context context) {
        String filePath = null;
        if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            filePath = context.getExternalFilesDir(null).getAbsolutePath();
        } else {
            filePath = context.getFilesDir().getAbsolutePath();
        }
        return filePath;
    }
}
